import React, { useEffect, useRef, useState } from 'react';
import './index.css';
import Title from "../../component/Title";
import request from "../../axios/index";
import dayjs from 'dayjs';
import { useSelector } from 'react-redux';
import { message, Segmented } from 'antd';
import { PullToRefreshify } from 'react-pull-to-refreshify';

// 定义设备数据类型
interface Device {
    deviceAlias: string;
    onlineStatus: string;
    cgid: string;
    loginCity: string;
    deviceModelCode: string | null;
}

interface CookType {
    merchantName: string | undefined;
    merchantId: string | undefined;
}

interface CookTypeData {
    data?: CookType[];
}

// 定义菜谱数据类型
interface Dish {
    recipeName: string;
    cookTimes: string | number;
    cookSpecCopies: string | number;
}

// 计算不算今天往前 30 天的日期范围
const getLast30DaysDateRange = () => {
    const today = new Date();
    // 获取当前日期的前一天作为结束日期
    const endDate = new Date(today.getTime() - 24 * 60 * 60 * 1000);
    // 获取 30 天前的日期作为起始日期
    const startDate = new Date(endDate.getTime() - 29 * 24 * 60 * 60 * 1000);
    return [startDate, endDate];
};



const MyComponent = () => {
    const counter: any = useSelector((state: any) => state.counter.data);
    const [device, setDevice] = useState<Device[]>([]);
    const [dish, setDish] = useState<Dish[]>([]);
    const [cookType, setCookType] = useState<string>("cook_times");
    const [isLoading, setIsLoading] = useState<boolean>(true);
    const [selectedValue, setSelectedValue] = useState<string | number | null | any>(null);
    const [allShop, setAllShop] = useState<CookTypeData>({});
    const [refreshing, setRefreshing] = useState<boolean>(false);
    const [page, setPage] = useState(1)
    const pageRef = useRef(page)
    const [status, setStatus] = useState<Boolean>(true)
    const scrollContainerRef = useRef<HTMLDivElement>(null);

    // 获取菜谱数据
    const getShopDish = async (id = '') => {
        if (!id) {
            return [];
        }
        try {
            const { data } = await request.get(`/route/api/merchant/recipes/${id}`, {
                accessToken: 1,
                limit: 10,
                startDate: dayjs(getLast30DaysDateRange()[0]).format("YYYY-MM-DD"),
                endDate: dayjs(getLast30DaysDateRange()[1]).format("YYYY-MM-DD"),
                type: cookType
            });
            setDish(data as Dish[]);
        } catch (error) {
            message.error('请求失败')
            console.error('获取菜谱数据失败:', error);
            return [];
        }
    };

    // 获取设备数据
    const getShopDev = async (id = '') => {
        if (!id) {
            return [];
        }
        setStatus(true)
        try {
            const { data } = await request.get(`/route/api/merchant/devices/${id}`, {
                accessToken: 1,
                pageNum: page,
                pageSize: 5
            });
            if (page === 1) {
                setDevice(data as Device[]);
            } else {
                setDevice((prevData: any) => {
                    return [...(prevData || []), ...(data as Device[] || [])]
                });
            }
        } catch (error) {
            message.error('请求失败')
            console.error('获取设备数据失败:', error);
            return [];
        } finally {
            setStatus(false)
        }
    };

    const getInitData = async (id = counter?.corpId ) => {
        try {
            const { data } = await request.get(`/route/api/merchant/getMerchantInCF/${id}`, {
                accessToken: 1,
            });
            const firstId = data?.data?.[0]?.merchantId;
            setSelectedValue(firstId);
            setAllShop(data);
            await handleChangeId(firstId);
        } catch (error) {
            message.error('请求失败')
            console.error("Error getting initial data:", error);
        }
    };

    const handleChangeId = async (val: any) => {
        setSelectedValue(val)
        await getShopDish(val);
        await getShopDev(val);
        setPage(1)
    };

    const renderText = (pullStatus: any, percent: any) => {
        switch (pullStatus) {
            case "pulling":
                return (
                    <div>
                        下拉即可刷新{" "}
                        <span style={{ color: "green" }}>{`${percent.toFixed(0)}%`}</span>
                    </div>
                );
            case "canRelease":
                return "释放即可刷新...";
            case "refreshing":
                return "刷新中";
            case "complete":
                return "刷新成功";
            default:
                return "";
        }
    };


    const handleRefresh = () => {
        setRefreshing(true);
        setPage(1);
        getInitData().then(() => {
            setRefreshing(false);
        });
    };

    let timer: any = null
    const handleScroll = (e: any) => {
        let scrollTop = e.target.scrollTop
        let scrollHeight = e.target.scrollHeight
        let offsetHeight = Math.ceil(e.target.getBoundingClientRect().height)
        let currentHeight = scrollTop + offsetHeight
        // if (timer) {
        //     clearTimeout(timer);
        // }
        console.log(currentHeight, scrollHeight)
        // timer = setTimeout(() => {
        if (currentHeight >= scrollHeight-1) {
            setPage(page + 1);
        }
        // }, 300); // 防抖时间为 300 毫秒，可按需调整
    };
    useEffect(() => {
        const fetchData = async () => {
            await getInitData()
            setIsLoading(false)
        };
        fetchData();
    }, []);

    useEffect(() => {
        getShopDev(selectedValue)
    }, [page])

    useEffect(() => {
        getShopDish(selectedValue)
    }, [cookType])

    useEffect(() => {
        const container = scrollContainerRef.current;
        if (container) {
            container.removeEventListener('scroll', handleScroll);
            container.addEventListener('scroll', handleScroll);
        }
        return () => {
            if (container) {
                container.removeEventListener('scroll', handleScroll);
            }
        };
    }, [status]);

    if (isLoading) {
        return <div>Loading...</div>;
    }

    return (
        <div className="container">
            <div style={{ width: '100%', overflowX: 'scroll' }}>
                <Segmented
                    onChange={handleChangeId}
                    value={selectedValue}
                    options={allShop?.data?.map((item) => ({ label: item.merchantName, value: item.merchantId })) || []}
                />
            </div>
            <Title title="客户设备" num={device?.length} />
            <div className="scrollable-container" ref={scrollContainerRef}>
                <PullToRefreshify
                    refreshing={refreshing}
                    onRefresh={handleRefresh}
                    renderText={renderText}
                >
                    {device?.length > 0 ? (
                        device?.map((item) => (
                            <div className="device-item" key={item.cgid}>
                                <div className="device-item-content">
                                    <div className="device-item-title">
                                        {item.deviceAlias}
                                    </div>
                                    <span className="device-address">{item.deviceModelCode}</span>
                                    <span className="device-info">{item.cgid}</span>
                                    <span className="device-address">{item.loginCity || '暂无地址'}</span>
                                </div>
                            </div>
                        ))
                    ) : (
                        <div style={{ textAlign: 'center' }}>暂无设备数据</div>
                    )}
                </PullToRefreshify>
            </div>
            <br />
            <Title title="客户菜谱" num={dish?.length} more={
                <>
                    {["cook_times", "cook_spec_copies"].map((item, ind) => (
                        <span
                            key={item}
                            onClick={() => setCookType(item)}
                            className={cookType === item ? "span-top10-count" : "span-top10-amount"}
                        >
                            {ind ? "份数Top10" : "次数Top10"}
                        </span>
                    ))}
                </>
            } />
            <div className="scrollable-container recipe-container">
                {dish?.length > 0 ? (
                    dish?.map((item) => (
                        <div className="recipe-item" key={item.recipeName}>
                            <div className="recipe-item-content">
                                <div className="recipe-item-title">
                                    {item.recipeName}
                                </div>
                                <div className="recipe-item-title" style={{ color: 'rgb(102,112,133)' }}>
                                    {cookType === "cook_times" ? `${item.cookTimes}次` : `${item.cookSpecCopies}份`}
                                </div>
                            </div>
                        </div>
                    ))
                ) : (
                    <div style={{ textAlign: 'center', width: '100%' }}>暂无菜谱数据</div>
                )}
            </div>
            <br />
        </div>
    );
};

export default MyComponent;
